﻿/*
ChessboardActivity.java - Source Code for XiangQi Wizard Android Edition

XiangQi Wizard Android Edition - a Chinese Chess Program for Android Platform
Designed by Jpcxc (jpcxc@126.com), Version: 0.1, Last Modified: April. 2011
Copyright (C) 2011-2015 www.xqbase.com and jpcxc@126.com

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
package cn.letlet.ui;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import cn.letlet.ui.ToggleButtonGroupTableLayout;
import android.view.View;
import android.widget.TableRow;

import cn.letlet.data.Data;
import cn.letlet.data.DbHelper;
import cn.letlet.utils.Debug;
import cn.letlet.util.AiThread;

import cn.letlet.xiangqi.R;

/**
 * The Class ChessboardActivity.
 */
public class ChessboardActivity extends Activity {
	
	AiThread aiThread ;

	/** The m board view. */
	ChessboadView mBoardView;

	/** The m text. */
	TextView mInfoTextView;

	/** The layout. */
	LinearLayout mLayout;

	/** The m helper. */
	DbHelper mHelper;

	SoundPool mPool;
	
	boolean mHasSound = true;

	HashMap<Integer, Integer> mSoundsMap = new HashMap<Integer, Integer>();

	/**
	 * Called when the activity is first created.
	 * 
	 * @param savedInstanceState
	 *            the saved instance state
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mLayout = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.game_board_layout, null);
		setContentView(mLayout);
		mPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
		mHasSound = getSharedPreferences("data", 0).getBoolean("sound", true);

		// 如果设置为有声音，则初始化。
		if (mHasSound) {
			initSounds();
		}

		loadConfigData();
		mHelper = new DbHelper(this);
		loadSavedGameData();
		mInfoTextView = (TextView) findViewById(R.id.text);
		//mBoardView = new ChessboadView(this, handler);
		mBoardView = ChessboadView.getInstance(this, handler);
		mLayout.addView(mBoardView);
		initPieceLayout();
		aiThread = new AiThread(this,handler);
		aiThread.start();
	}

	void initSounds() {
		for (int i = 0; i < Data.SOUND_ID.length; i++) {
			mSoundsMap.put(i, mPool.load(this, Data.SOUND_ID[i], 1));
		}
	}

	void playSound(int response) {
		if (mHasSound) {
			mPool.play(mSoundsMap.get(response), 1.0f, 1.0f, 1, 0, 1.0f);
		}
	}

	/**
	 * Load data.
	 */
	void loadConfigData() {
		SharedPreferences data = getSharedPreferences("data", 0);
		int w = data.getInt("who", 0);
		int h = data.getInt("handicap", 0);
		int l = data.getInt("level", 0);
		Data.rsData[16] = (byte) w;
		Data.rsData[17] = (byte) h;
		Data.rsData[18] = (byte) l;
	}

	/**
	 * Load saved game data.
	 */
	void loadSavedGameData() {
		SQLiteDatabase db = mHelper.getReadableDatabase();
		Cursor c = db.query(DbHelper.TABLE_NAME, null, null, null, null, null,
				null);
		if (c.moveToFirst()) {
			byte[] data = c.getBlob(c.getColumnIndex(DbHelper._DATA));
			Data.rsData = data;
		}
		c.close();
		db.close();
	}

	/** The handler. */
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
//			Debug.e("Text " + mInfoTextView.getVisibility() + " "
//					+ mInfoTextView.getText());
			super.handleMessage(msg);
			switch (msg.what) {
			case Data.WHAT_THINKING:
				mInfoTextView.setText(getResources().getString(
						R.string.info_thinking));
				break;
			case Data.WHAT_SOUND:
				playSound(msg.arg1);
				if (msg.obj != null) {
					mInfoTextView.setText((String) msg.obj);
				}
				if(msg.arg2 == Data.WHAT_GAMEEND){
					dialog((String) msg.obj);
				}
			case Data.WHAT_OTHER:
				mInfoTextView.setText((String) msg.obj);
				break;
			case Data.WHAT_ALERT:
				dialog((String)msg.obj);
			}
		}
	};

	/**
	 * Inits the piece layout.
	 */
	private void initPieceLayout() {
		Display display = getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();
		Debug.i("Screen size: " + width + "x" + height);
		checkScreen(width);
	}

	/**
	 * Check screen.
	 * 
	 * @param width
	 *            the width
	 */
	private void checkScreen(int width) {
		if (width < Data.LOW_SCREEN_WIDTH) {
			AlertDialog.Builder b = new AlertDialog.Builder(this);
			b.setTitle(R.string.info_title);
			b.setMessage(R.string.info_not_support);
			b.setPositiveButton(R.string.text_positive_button,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
			b.create().show();
		}
	}

	/**
	 * Re play.
	 */
	private void rePlay() {
		Data.reInit();
		loadConfigData();
		mBoardView.init();
		mBoardView.load();
		mBoardView.paint();
		mBoardView.initThe();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem restart = menu.add(R.string.text_restart);
		restart.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				if (mBoardView.phase == ChessboadView.PHASE_THINKING) {
					Toast.makeText(getApplicationContext(), "电脑思考中，请稍等再试...",
							Toast.LENGTH_LONG).show();
					return true;
				}
				rePlay();
				return true;
			}
		});
		MenuItem setting = menu.add(R.string.text_setting);
		setting.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				AlertDialog.Builder b = new AlertDialog.Builder(
						ChessboardActivity.this);
				b.setTitle(R.string.text_setting);
				LinearLayout setting = (LinearLayout) LayoutInflater.from(
						ChessboardActivity.this).inflate(
						R.layout.setting_layout, null);
				final SharedPreferences data = getSharedPreferences("data", 0);
				final Editor editor = data.edit();

				RadioGroup who = (RadioGroup) setting
						.findViewById(R.id.group_who);
				int w = data.getInt("who", 0);
				who.getChildAt(0).setId(0);
				who.getChildAt(1).setId(1);
				RadioButton wrb = (RadioButton) who.getChildAt(w);
				wrb.setChecked(true);
				who.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						editor.putInt("who", checkedId);
						editor.commit();
						Debug.e(checkedId + " ID");
					}
				});

				RadioGroup handicap = (RadioGroup) setting
						.findViewById(R.id.group_handicap);
				int h = data.getInt("handicap", 0);
				handicap.getChildAt(0).setId(0);
				handicap.getChildAt(1).setId(1);
				handicap.getChildAt(2).setId(2);
				handicap.getChildAt(3).setId(3);
				RadioButton hrb = (RadioButton) handicap.getChildAt(h);
				hrb.setChecked(true);
				handicap.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						editor.putInt("handicap", checkedId);
						Debug.e(checkedId + " ID");
						editor.commit();
					}
				});

//				RadioGroup level = (RadioGroup) setting
//						.findViewById(R.id.group_level);
//				int l = data.getInt("level", 0);
//				level.getChildAt(0).setId(1);
//				level.getChildAt(1).setId(2);
//				level.getChildAt(2).setId(3);
//				level.getChildAt(3).setId(4);
//				level.getChildAt(4).setId(5);
//				level.getChildAt(5).setId(6);
//				level.getChildAt(6).setId(7);
//				RadioButton lrb = (RadioButton) level.getChildAt(l);
//				lrb.setChecked(true);
//				level.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//					@Override
//					public void onCheckedChanged(RadioGroup group, int checkedId) {
//						editor.putInt("level", checkedId);
//						editor.commit();
//					}
//				});
				final ToggleButtonGroupTableLayout level = (ToggleButtonGroupTableLayout) setting
						.findViewById(R.id.tabled_group_level);
				int l = data.getInt("level", 0);
				if(l<1){
					l=1;
				}
				TableRow levelRow0= (TableRow)level.getChildAt(0);
				TableRow levelRow1= (TableRow)level.getChildAt(1);
				//TableRow levelRow2= (TableRow)level.getChildAt(2);
				levelRow0.getChildAt(0).setId(1);
				levelRow0.getChildAt(1).setId(2);
				levelRow0.getChildAt(2).setId(3);
				levelRow1.getChildAt(0).setId(4);
				levelRow1.getChildAt(1).setId(5);
				levelRow1.getChildAt(2).setId(6);
//				if(l<4){
//					Debug.d(String.valueOf(l));
//					RadioButton lrb = (RadioButton)levelRow0.getChildAt(l);
//					lrb.setChecked(true);
//				}else{
//					RadioButton lrb = (RadioButton)levelRow1.getChildAt(l);
//					lrb.setChecked(true);
//				}
				
				CheckBox sound = (CheckBox) setting
						.findViewById(R.id.sound);
				boolean s = data.getBoolean("sound", true);
				sound.setChecked(s);
				sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						editor.putBoolean("sound", isChecked);
						editor.commit();
						mHasSound = isChecked;
					}
				});

				b.setView(setting);
				b.setPositiveButton("保存", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 如果设置为有声音，则初始化。
						if (mHasSound) {
							initSounds();
						}
						int checkedId = level.getCheckedRadioButtonId();
						Debug.d("checked id:"+checkedId);
						editor.putInt("level",checkedId);
						editor.commit();
					}
				});
				b.setNegativeButton("重来",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								if (mBoardView.phase == ChessboadView.PHASE_THINKING) {
									Toast.makeText(getApplicationContext(),
											"设置已保存，电脑思考中，请稍等再试...",
											Toast.LENGTH_LONG).show();
									return;
								}
								rePlay();
								// 如果设置为有声音，则初始化。
								if (mHasSound) {
									initSounds();
								}
							}
						});
				b.create().show();
				return true;
			}
		});
		MenuItem about = menu.add(R.string.text_about);
		about.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				AlertDialog.Builder b = new AlertDialog.Builder(
						ChessboardActivity.this);
				b.setTitle(R.string.text_about);
				TextView msgText = new TextView(ChessboardActivity.this);
				msgText.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				msgText.setPadding(10, 0, 10, 0);
				msgText.setTextSize(16);
				msgText.setText(R.string.info_about);
				b.setView(msgText);
				b.setPositiveButton(R.string.text_positive_button, null);
				b.create().show();
				return true;
			}
		});
		MenuItem exit = menu.add(R.string.text_exit);
		exit.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				SQLiteDatabase db = mHelper.getWritableDatabase();
				Cursor c = db.query(DbHelper.TABLE_NAME, null, null, null,
						null, null, null);
				Data.rsData[16] = (byte) (Data.flipped ? 1 : 0);
				Data.rsData[17] = (byte) Data.handicap;
				Data.rsData[18] = (byte) Data.level;
				ContentValues values = new ContentValues();
				values.put(DbHelper._DATA, Data.rsData);
				if (c.moveToFirst()) {
					// 如果数据存在，就更新
					db.update(DbHelper.TABLE_NAME, values, null, null);
				} else {
					// 数据不存在，就插入
					db.insert(DbHelper.TABLE_NAME, null, values);
				}
				c.close();
				db.close();
				onDestroy();
				finish();
				System.exit(0);
				return true;
			}
		});
		return super.onCreateOptionsMenu(menu);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			//mBoardView.retract();
			mBoardView.aiTips();
			return true;
		}
		return false;
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mBoardView.releaseSource();
		aiThread = null;
	}
	
	protected void dialog(String messsage) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage(messsage);
		builder.setTitle("提示");
		builder.setPositiveButton("再来一局？", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				rePlay();
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
	
}